/**
 * 
 */
package com.maoye.ossp.biz.statement.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import com.hotent.base.api.query.QueryFilter;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.impl.SupplierServiceImpl;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.entity.MarketAssociated;
import com.maoye.ossp.biz.contract.entity.SelfAssociated;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.IMarketAssociatedService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.statement.entity.StatementInvoice;
import com.maoye.ossp.biz.statement.entity.StatementMainConsortium;
import com.maoye.ossp.biz.statement.entity.StatementInvoiceDetail;
import com.maoye.ossp.biz.statement.service.StatementInvoiceService;
import com.maoye.ossp.biz.statement.util.excel.ExcelOperatorConstant;
import com.maoye.ossp.biz.statement.util.excel.JExcelOperator;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.util.ConvertUtils;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.utils.SysDictUtils;
import com.maoye.ossp.sys.org.util.UserUtils;

/**
 * 
 * 
 * @author xiaohan
 * @date 2014年2月24日
 * @version
 * @filename 
 *           com.maoye.ossp.biz.statement.controller.StatementInvoiceController.java
 */
@Controller
@RequestMapping(value = "/biz/statement/invoice")
public class StatementInvoiceController extends BaseController {

	@Resource
	private StatementInvoiceService statementInvoiceService;
	
	@Resource
	private ISupplierService supplierService;
	@Resource
	private SupplierServiceImpl supplierServiceImpl;
	
	@Resource
	private IContractService contractService;
	
	@Resource
	private IAdvertAssociatedService advertAssociatedService;
	
	@Resource
	private ILeaseAssContractService leaseAssContractService;
	
	@Resource
	private ISelfAssociatedService selfAssociatedService;
		
	@Resource
	private IMarketAssociatedService marketAssociatedService;
	
	
	private void invoiceTypeHandler(StatementInvoice invoice) {
		if (invoice != null) {
			invoice.setInvoiceType(SysDictUtils.getValue(
					ConvertUtils.ConstantUtils.ST_STATEMENTINVOICE_TYPE,
					invoice.getInvoiceType()));
		}
	}

	private void invoiceTypeHandler(List<StatementInvoice> list) {
		if (list != null && list.size() > 0) {
			for (StatementInvoice statementInvoice : list) {
				invoiceTypeHandler(statementInvoice);
			}
		}
	}

	@RequestMapping(value = "/list")
	public String list(StatementInvoice statementInvoice,
			HttpServletRequest request, Model model) {
		
		// 获取登陆用户Id
		Long userId = UserUtils.getCurrentUserId();
		// 根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier = supplierServiceImpl.get(userId);
		QueryFilter queryFilter = getQuerFilter(request, statementInvoice);
		// 设置供应商编码
		if (supplier != null) {
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(),
					QueryOP.EQUAL);
		}			
		Page<StatementInvoice> page = (Page<StatementInvoice>) statementInvoiceService
				.find(queryFilter);
		model.addAttribute("page", page);
		model.addAttribute("statementInvoice", statementInvoice);
		return resultPage("/biz/statement/invoice/supplies/list", model,
				request);
	}

	/**
	 * 导出列表
	 * 
	 * @param entity
	 * @param request
	 * @param response
	 * @author xiaohan
	 * @data 2014年2月18日
	 */
	@RequestMapping(value = "/export/list")
	public void exportToExcel(StatementInvoice entity,
			HttpServletRequest request, HttpServletResponse response) {
		List<StatementInvoice> list = statementInvoiceService.getList(
				ConvertUtils.convertObj2Map(entity), 0, -1);
		JExcelOperator jExcelOperator = new JExcelOperator();
		invoiceTypeHandler(list);
		// 导出到excel,并将导出文件发往客户端
		jExcelOperator.exportExcel(request, response,
				ExcelOperatorConstant.COLUMN_STATEMENTINVOICE,
				ExcelOperatorConstant.FIELD_STATEMENTINVOICE, list);
	}

	/**
	 * 导出单条
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @author xiaohan
	 * @data 2014年2月18日
	 */
	@RequestMapping(value = "/export/{id}/detail")
	public void exportDetailToExcel(@PathVariable Long id,
			HttpServletRequest request, HttpServletResponse response) {
		StatementInvoice invoice = statementInvoiceService.get(id);
		try {
			// 设置输出的格式
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			// 获取浏览器类型
			String user_agent = request.getHeader("User-Agent").toLowerCase();
			String fileName = "";
			// 为不同的浏览器，对文件名进行不同的编码转换
			if (user_agent.indexOf("firefox") > 0) {
				fileName = new String("供应商开票信息".getBytes("UTF-8"), "iso8859-1");
			} else {
				fileName = URLEncoder.encode("供应商开票信息", "UTF-8");
			}
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName + ".xls");
			OutputStream os = response.getOutputStream();
			statementInvoiceService
					.exportInvoiceAndDetail(invoice, os);;
			response.flushBuffer();
		} catch (IOException ex) {
			System.out.println("导出数据出错");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	@RequestMapping(value = "/view")
	public String getObjByID(Model model,HttpServletRequest request, StatementInvoice invoice) {
		/*Long userId=UserUtils.getCurrentUserId();
		Supplier supplier=supplierService.getBaseInfoById(userId);
		String flag="0";
		if(supplier!=null&&supplier.getSupplierType().equals("SUPPLIER")){
			flag="1";
		}*/
		Long id=Long.parseLong(request.getParameter("id"));
		invoice = statementInvoiceService.get(id);
		model.addAttribute("statementInvoice", invoice);
		//model.addAttribute("flag",flag);
	    return "/biz/statement/invoice/supplies/view";
	}
	
	
	
	@RequestMapping(value = "/print")
	public String print(Model model,HttpServletRequest request, StatementInvoice invoice) {
		Long id=Long.parseLong(request.getParameter("id"));
		invoice = statementInvoiceService.get(id);
		model.addAttribute("statementInvoice", invoice);
		//model.addAttribute("flag",flag);
	    return "/biz/statement/invoice/supplies/print";
	}
    
	@RequestMapping(value = "/update/view")
	public String openDetailView(Model model,StatementInvoice invoice) {
	/*	invoice.setSupplierName("测试供应商");
		invoice.setSupplierNo("D0001");*/
		/*Long id=invoice.getId();*/
		/*StatementInvoice a=statementInvoiceService.get(invoice.getId());*/
		//invoice = statementInvoiceService.get(Long.parseLong("74340000000001008"));
		StatementInvoice invoice1=new StatementInvoice ();
		invoice1=statementInvoiceService.get(invoice.getId());
		 String taxRate="";
		 String taxType="";
		 String taxRateCode="";
		if(invoice1.getContractType().equals("Z100")){
			Map map=contractService.getBrandByContractNo(invoice1.getContractNumber().substring(5));
			if(map!=null){
		    AssociatedContract associatedContract=(AssociatedContract) map.get("contract");
		    if(associatedContract!=null){
			taxRate=associatedContract.getTaxRate();
			taxRateCode=associatedContract.getTaxRateCode();
			taxType=associatedContract.getTaxType();
		    }
			}//自营合同
		}else if(invoice1.getContractType().equals("Z300")||invoice1.getContractType().equals("Z400")){
			Map map=selfAssociatedService.getBrandByContractNo(invoice1.getContractNumber().substring(5));
			if(map!=null){
				SelfAssociated selfAssociated=(SelfAssociated) map.get("contract");
				if(selfAssociated!=null){
				taxRate=selfAssociated.getTaxRate();
				taxRateCode=selfAssociated.getTaxRateCode();
				taxType=selfAssociated.getTaxType();
				}

			}
		}else if(invoice1.getContractType().equals("Z200")){
			Map map=leaseAssContractService.getBrandByContract(invoice1.getContractNumber().substring(5));
			if(map!=null){
				LeaseAssociated leaseAssociated=(LeaseAssociated) map.get("contract");
				if(leaseAssociated!=null){
				taxRate=leaseAssociated.getTaxRate();
				taxRateCode=leaseAssociated.getTaxRateCode();
				taxType=leaseAssociated.getTaxType();
				}

			}
		}else if(invoice1.getContractType().equals("Z500")){
			Map map=advertAssociatedService.getBrandByContractNo(invoice1.getContractNumber().substring(5));
			if(map!=null){
				AdvertAssociated advertAssociated=(AdvertAssociated) map.get("contract");
				if(advertAssociated!=null){
				taxRate=advertAssociated.getTaxRate();
				taxRateCode=advertAssociated.getTaxRateCode();
				taxType=advertAssociated.getTaxType();
				}

			}
		}else if(invoice1.getContractType().equals("Z600")){
			Map map=marketAssociatedService.getBrandByContractNo(invoice1.getContractNumber().substring(5));
			if(map!=null){
				MarketAssociated marketAssociated=(MarketAssociated) map.get("contract");
				if(marketAssociated!=null){
				taxRate=marketAssociated.getTaxRate();
				taxRateCode=marketAssociated.getTaxRateCode();
				taxType=marketAssociated.getTaxType();
				}

			}
	}
		if(taxRateCode.equals("R0")){
			invoice1.setTaxRateCode("J0");
		}else if(taxRateCode.equals("R1")){
			invoice1.setTaxRateCode("J1");
		}else if(taxRateCode.equals("R2")){
			invoice1.setTaxRateCode("J4");
		}else if(taxRateCode.equals("R3")){
			invoice1.setTaxRateCode("J5");
		}
		if(taxRate.equals("0")){
		  invoice1.setTaxRateName(taxRate+"%"+taxType);
		}else{
			  invoice1.setTaxRateName(taxRate+taxType);

		}
		
		if(taxRate.equals("17%")){
			invoice1.setTaxRate(17.0);
		}else if(taxRate.equals("13%")){
			invoice1.setTaxRate(13.0);
		}
		
		//invoiceTypeHandler(invoice1);
		/*model.addAttribute("obj", invoice);*/
		model.addAttribute("detailSize",invoice1.getInvoiceDetailList().size());
		model.addAttribute("statementInvoice", invoice1);
		//return "/biz/statement/invoice/supplies/edit";
		return "/biz/statement/invoice/supplies/edit";
	}

	/**
	 * @param type
	 *            结算单类型
	 * @param model
	 * @return
	 * @author xiaohan
	 * @data 2014年3月17日
	 */
	@RequestMapping(value = "/add/view")
	public String openAddView(StatementInvoice invoice, Model model) {
		if (StringUtils.isEmpty(invoice.getInvoiceType())) {
			invoice.setInvoiceType("1");
		}	
		invoiceTypeHandler(invoice);
		model.addAttribute("statementInvoice", invoice);
		return "/biz/statement/invoice/supplies/add";
	}

	/**
	 * @param type
	 *            结算单类型
	 * @param model
	 * @return
	 * @author xiaohan
	 * @data 2014年3月17日
	 */
	@RequestMapping(value = "/add/ext/view")
	public String openAddViewWithOutLink(StatementInvoice invoice, Model model) {
		StringBuilder errorInfo = new StringBuilder();
		// 传入
		if (StringUtils.isEmpty(invoice.getInvoiceType())) {
			errorInfo.append("发票类型错误");
		} else {
			invoiceTypeHandler(invoice);
			errorInfo.append("发票类型错误");
		}
		if (StringUtils.isEmpty(invoice.getSupplierNo())
				|| StringUtils.isEmpty(invoice.getSupplierName())) {
			errorInfo.append("供应商编号，供应商名称不能为空");
		}
		model.addAttribute("obj", invoice);
		return "/biz/statement/invoice/supplies/add";
	}

	@RequestMapping(value = "/update")
	public String update(StatementInvoice entity,
			RedirectAttributes redirectAttributes) {
		boolean isSuccess = statementInvoiceService
				.updateSupplierReceipt(entity) > 0;
		addMessage(redirectAttributes, isSuccess ? "操作成功！" : "操作失败！");
		return "redirect:/biz/statement/invoice/list";
	}

	@RequestMapping(value = "/add")
	public String add(@ModelAttribute StatementInvoice statementInvoice,
			Model model, HttpServletRequest request) throws Exception {
		String flag=request.getParameter("flag");
		statementInvoice.setFlag(flag);
		Long invoiceId =statementInvoiceService.add(statementInvoice);
		boolean isSuccess =invoiceId>0;
		if (!isSuccess) {
			model.addAttribute("obj", statementInvoice);
			addMessage(model, "添加失败");
			return "/biz/statement/invoice/supplies/add";
		}
		model.addAttribute("invoiceId",invoiceId.toString());
		return resultPage(SUCCESS_TICKET, model, request);
	}
	
	@RequestMapping(value = "/saveUpdate")
	public String saveUpdate(@ModelAttribute StatementInvoice statementInvoice,
			Model model, HttpServletRequest request) throws Exception {
		boolean isSuccess = statementInvoiceService.saveUpdate(statementInvoice) > 0;
		if (!isSuccess) {
			model.addAttribute("statementInvoice", statementInvoice);
			addMessage(model, "修改失败");
			return "/biz/statement/invoice/supplies/edit";
		}
		return resultPage(SUCCESS, model, request);
	}
	
	@RequestMapping(value = "/{id}/delete")
	public String deleteSR(@PathVariable String id,
			RedirectAttributes redirectAttributes) {
		boolean isSuccess = statementInvoiceService.deleteSupplierReceipt(id) > 0;
		// return RequestParamHandler.createResultJson(count==1);
		addMessage(redirectAttributes, isSuccess ? "操作成功！" : "操作失败！");
		return "redirect:/biz/statement/invoice/list";
	}

	@RequestMapping(value = "/approval/{id}")
	public String approval(@PathVariable Long id, Model model) {
		 StatementInvoice invoice = statementInvoiceService.get(id);
		/* if(!invoice.getApprover().equals(String.valueOf(UserUtils.getCurrentUserId()))){
		   return _403;
	    }  */
		model.addAttribute("statementInvoice", invoice);
		return "/biz/statement/invoice/supplies/approval";
	}

	@RequestMapping(value = "/approval")
	public String approval(StatementInvoice entity,
			RedirectAttributes redirectAttributes) throws Exception {
		statementInvoiceService.approval(entity);
		return SUCCESS;
	}

}
